import requests
import  json
url = 'http://www.kfc.com.cn/kfccda/ashx/GetStoreList.ashx?op=cname'
city_name = input('请输入要查询的城市：')
from_data = {
    'cname': city_name,
    'pageIndex': 1,
    'pageSize': 10
}
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.66 Safari/537.36'
}
# 先发送一次请求，然后获取到一共有多少家 rowcount
res = requests.post(url,headers = headers,data= from_data)
# 餐厅的总数量
total_count = int (res.json()['Table'][0]['rowcount'])
# 请求的总页数
page_count = total_count//10 + 1
#第一页的数据列表
data_list = (res.json ()['Table1'])
for page in range(2,page_count):

    data ={
        'cname': city_name,
        'pageIndex': page,
        'pageSize': 10
    }
    #针对每一页去发起数据请求
    response = requests.post(url,headers = headers ,data = data)
    new_list = response.json()['Table1']
    data_list.extend(new_list)

#存储结果：
# data_list 存储为json格式，文件名就是城市名
with open(f'{city_name}.json',mode='w',encoding='utf-8') as f:
    json.dump(data_list,fp= f,ensure_ascii=False)
    print('查询结果存储成功！！')